package com.jiubanqingchen.framework.security.admin;

import com.jfinal.aop.Aop;
import com.jiubanqingchen.framework.consts.CacheKey;
import com.jiubanqingchen.framework.exception.WishException;
import com.jiubanqingchen.framework.exception.WishExceptionKey;
import com.jiubanqingchen.framework.security.AuthService;
import com.jiubanqingchen.kit.ApplicationKit;
import com.jiubanqingchen.kit.BlankKit;
import com.jiubanqingchen.model.models.Dept;
import com.jiubanqingchen.model.models.Role;
import com.jiubanqingchen.plugin.cache.redis.kit.CacheKit;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author light_dust
 * @since 2021/1/16 11:54
 */
public class AdminUserService {

    /**
     * 获取admin user cache key
     * @param userId userid
     */
    private String getCacheKey(String userId){
        return CacheKey.ADMIN_USER.replace("#(userId)", userId);
    }

    /**
     * 创建adminUser
     *
     * @param userId      用户id
     * @param userAccount 用户账号
     * @param userName    用户名称
     */
    public AdminUser createAdminUser(String userId, String userAccount, String userName) throws WishException {
        AuthService authService= Aop.get(AuthService.class);
        AdminUser adminUser = new AdminUser();
        adminUser.setUserId(userId);
        adminUser.setUserAccount(userAccount);
        adminUser.setUserName(userName);
        //我们需要查询当前用户的角色信息 如果当前用户没有角色则视为不允许登录用户 因为资源是与角色挂钩的
        List<Role> roleList = authService.getUserRole(userId);
        if (BlankKit.isBlankList(roleList)) throw new WishException(WishExceptionKey.USER_NOT_ASSIGN_ROLE);
        adminUser.setRoleList(roleList.stream().map(Role::getRoleId).collect(Collectors.toList()));
        //拿到用户的主要部门信息
        Dept mainDept = authService.getUserMainDept(userId);
        if (mainDept != null) {
            adminUser.setMainDeptId(mainDept.getDeptId());
            adminUser.setMainDeptName(mainDept.getDeptName());
        }
        CacheKit.me().getCache().setex(getCacheKey(userId), ApplicationKit.me().getTokenEffective(), adminUser);
        return adminUser;
    }

    /**
     * 删除 admin user
     * @param userId 用户id
     */
    public void deleteAdminUser(String userId){
        CacheKit.me().getCache().del(getCacheKey(userId));
    }
}
